#!/bin/bash

### BEGIN INIT INFO
# Provides:          ivic-daemon
# Required-Start:    $network $syslog
# Required-Stop:     $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start ivic-daemon at boot time
# Description:       Enable service provided by ivic-daemon.
### END INIT INFO

# /etc/init.d/ivic-daemon {start | stop | restart}

DAEMON=$PREFIX/usr/sbin/ivic-daemon
DESC="iVIC Daemon"
PIDFILE=$PREFIX/var/run/ivic/daemon.pid

[ -z $DEBUG ] && OUTDEV=/dev/null || OUTDEV=/dev/fd/0

[ -x $DAEMON ] || exit 0

check_pid() {
  PID=`cat $PIDFILE`
  if ps $PID > /dev/null 2>&1 
  then
    echo 'failed (already started)'
    exit 1
  fi
  rm -f $PIDFILE
}

start_server () {
  [ -f $PIDFILE ] && check_pid
  $DAEMON #> $OUTDEV 2>&1
}

stop_server () {
  [ ! -f $PIDFILE ] && echo 'failed (no pid file)' && exit 1
  PID=`cat $PIDFILE`
  kill $PID > /dev/null 2>&1 && return
  echo 'failed (not running)'; exit 1
}

case "$1" in
start)
  echo -n "Starting $DESC: "
  start_server
  echo 'success'
  ;;

stop)
  echo -n "Stopping $DESC: "
  stop_server
  echo 'success'
  ;;

restart)
  $0 stop
  sleep 1
  $0 start
  ;;

*)
  echo "Usage: $0 {start|stop|restart}" >&2
  exit 1
  ;;
esac

exit 0

